package com.makingTeam.server.controller.test;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import com.alibaba.fastjson.JSON;

import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SseController {

    public static final ConcurrentHashMap<String, SseEmitter> SSE_MAP = new ConcurrentHashMap<>();

    public SseEmitter sseEmitter() throws IOException {

        SseEmitter emitter = new SseEmitter(0L);
        // 链接建立完成之后，需要发送消息给客户端
        String sseEmitterId = UUID.randomUUID().toString();
        SSE_MAP.put(sseEmitterId, emitter);

        // 发送消息，发送客户端的唯一标识会给客户端
        Map<String, Object> msgMap = new HashMap<>();
        msgMap.put("clientId", sseEmitterId);
        emitter.send(SseEmitter.event().data(JSON.toJSONString(msgMap)));

        // 发送进入直播间的消息
        noticeClient(sseEmitterId, sseEmitterId.substring(0, 5) + "*** 进入了直播间");

        emitter.onCompletion(() -> {
            log.info("SSE操作完毕，连接关闭");
            SSE_MAP.remove(sseEmitterId);
            // 发送离开直播间的消息
            noticeClient(sseEmitterId, sseEmitterId.substring(0, 5) + "*** 离开了直播间");
        });

        return emitter;

    }

    private void noticeClient(String sseEmitterId, String message) {
        // 发送消息，在线人数加1
        Map<String, Object> msgMap = new HashMap<>();
        msgMap.put("msg", message);
        msgMap.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        msgMap.put("sessionId", sseEmitterId.substring(0, 5) + "***");
        msgMap.put("count", SSE_MAP.values().size());

        SSE_MAP.values().forEach(item -> {
            try {
                item.send(SseEmitter.event().data(JSON.toJSONString(msgMap)));
                log.info("发送消息完成");
            } catch (IOException e) {
                log.error("发送消息异常......", e);
            }
        });
    }
}
